﻿using System;
using System.Collections.ObjectModel;
using System.Reactive;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using SensorDrone.Net;

namespace SensorDroneStudio.Models
{
    public class TimeValue
    {
        public TimeSpan Time { get; set; }
        public double Value { get; set; }
    }

    public class SensorPlotModel : ISensorPlotModel
    {
        private readonly PlotModel _model;
        private readonly DateTimeOffset _now = new DateTimeOffset(DateTime.UtcNow);
        private ObservableCollection<TimeValue> _samples;

        public SensorPlotModel()
        {
            _model = new PlotModel();
            _model = new PlotModel("") {Background = OxyColors.Black, TitleColor = OxyColors.White};
            Model.Axes.Add(new TimeSpanAxis(AxisPosition.Bottom, null)
            {
                AxislineColor = OxyColors.White
            });
            Samples = new ObservableCollection<TimeValue>
            {
                new TimeValue {Time = _now.AddSeconds(1).Subtract(_now), Value = 1.0},
                new TimeValue {Time = _now.AddSeconds(2).Subtract(_now), Value = 1.5}
            };
            Model.Axes.Add(new LinearAxis(AxisPosition.Left, 0, 0)
            {
                AxislineColor = OxyColors.Green,
                MinimumPadding = 0.50,
                MaximumPadding = 0.50
            });
            var series = new LineSeries
            {
                MarkerType = MarkerType.Circle,
                Color = OxyColors.Green,
                ItemsSource = Samples,
                DataFieldX = "Time",
                DataFieldY = "Value"
            };

            Model.Series.Add(series);
        }

        public ObservableCollection<TimeValue> Samples
        {
            get { return _samples; }
            set { _samples = value; }
        }

        public PlotModel Model
        {
            get { return _model; }
        }

        public void Clear()
        {
            Samples.Clear();
        }

        public void Add(Timestamped<Reading> reading)
        {
            var sample = new TimeValue
            {
                Time = reading.Timestamp.Subtract(_now),
                Value = double.Parse(reading.Value.Value)
            };
            _samples.Add(sample);
            if (_samples.Count > 100)
            {
                _samples.RemoveAt(0);
            }
            Model.Axes[1].Maximum = Math.Max(sample.Value + (sample.Value*0.2), Model.Axes[1].Maximum);

            Model.RefreshPlot(true);
        }
    }
}